<?php

namespace App\Http\Middleware;

use function base64_encode;
use Closure;
use Request;
use Cookie;
use Session;
use EasyWeChat\Factory;
use function strpos;

class WechatAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $config = [
            'app_id'        => config('wechat.appid'),
            'secret'        => config('wechat.appsecret'),
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_base'],
                'callback' => '/r/oauth' . '?target_url=' . base64_encode(Request::fullUrl()),
            ],
        ];

        \Log::info('WechatAuthMiddleware');
        \Log::info('WechatAuthMiddleware url:' . Request::fullUrl());
        if (strpos(Request::fullUrl(), '/r/oauth') === false) {
            $open_id = Cookie::get('open_id');
            $type = Request::get('type');
            $id = Request::get('id');

            if ($type == 1) {
                \Log::info('typetypetypetypetypetypetypetypetype');
                \Log::info('1111111111111111111111111111111111111');
                session()->put(['target_url'=>Request::getRequestUri()]);
                session()->save();

                $config['oauth'] = [
                    'scopes'   => ['snsapi_base'],
                    'callback' => '/r/oauth' . '?target_url=' . base64_encode("http://dz.ddjuly.com/wechat/pay/index?id={$id}&type={$type}"),
                    //'target_url' => base64_encode(Request::getRequestUri()), /*. '?target_url=' . base64_encode(Request::getRequestUri())*/
                ];

                $app   = Factory::officialAccount($config);
                $oauth = $app->oauth;
                \Log::info('WechatAuthMiddleware 准备跳转');
                return $oauth->redirect();
            } else if ($type == 2) {
                \Log::info('typetypetypetypetypetypetypetypetype');
                \Log::info('22222222222222222222222222222222222');
                session()->put(['target_url'=>Request::getRequestUri()]);
                session()->save();

                $config['oauth'] = [
                    'scopes'   => ['snsapi_userinfo'],
                    'callback' => '/r/oauth' . '?target_url=' . base64_encode("http://dz.ddjuly.com/wechat/index/bindWechat?type={$type}"),
                ];

                $app   = Factory::officialAccount($config);
                $oauth = $app->oauth;
                \Log::info('WechatAuthMiddleware 准备跳转');
                return $oauth->redirect();
            } else {
                \Log::info('elseelseelseelseelseelseelseelseelse');
                \Log::info('333333333333333333333333333333333333');
                if ($this->is_weixin() && empty($open_id)) {
                    \Log::info('session_url:' . Request::fullUrl());
                    //Session::put('target_url', Request::getRequestUri());
                    //Session::save();

                    session()->put(['target_url'=>Request::fullUrl()]);
                    session()->save();
                    $config['oauth'] = [
                        'scopes'   => ['snsapi_base'],
                        'callback' => '/r/oauth' . '?target_url=' . base64_encode(Request::fullUrl()),
                        //'target_url' => base64_encode(Request::getRequestUri()), /*. '?target_url=' . base64_encode(Request::getRequestUri())*/
                    ];

                    $app   = Factory::officialAccount($config);
                    $oauth = $app->oauth;
                    \Log::info('WechatAuthMiddleware 准备跳转');
                    return $oauth->redirect();
                }
            }

        }

        $response = $next($request);
        //foreach($headers as $key => $value)
        //    $response->header($key, $value);

        return $response;

    }


    function is_weixin(){
        if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }


}
